<?php
session_start();

// 初始化数据库连接
$host = 'localhost';
$db   = 'dev_community';
$user = 'root';
$pass = 'root';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

// 检查用户是否登录，并获取用户名
$userLoggedIn = isset($_SESSION['user_id']);
if ($userLoggedIn) {
    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
}

// 每页显示的帖子数量
$postsPerPage = 8;

// 获取当前页码
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
if ($page < 1) {
    $page = 1;
}

// 计算偏移量
$offset = ($page - 1) * $postsPerPage;

// 计算总帖子数量
$stmt = $pdo->query("SELECT COUNT(*) AS total_posts FROM questions");
$totalPosts = $stmt->fetch()['total_posts'];

// 计算总页数
$totalPages = ceil($totalPosts / $postsPerPage);

// 分页查询所有帖子及其最新的回答时间
$stmt = $pdo->query("
    SELECT 
        q.id, 
        q.title, 
        q.content, 
        q.view_count, 
        q.created_at, 
        (SELECT COUNT(*) FROM answers WHERE question_id = q.id) AS answer_count,
        (SELECT MAX(created_at) FROM answers WHERE question_id = q.id) AS latest_answer_at
    FROM 
        questions q
    ORDER BY 
        q.created_at DESC
    LIMIT $postsPerPage OFFSET $offset
");
$posts = $stmt->fetchAll();
?>



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智界论坛</title>
    <link rel="stylesheet" type="text/css" href="./css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="./css/qs.css"/>
</head>

<body>
<div class="panel">
    <div class="panel-heading">
        <h2>智界论坛</h2>
        <div class="header-actions">
            <div class="button-group">
                <?php 

                // 如果用户未登录，显示登录/注册链接；如果已登录，显示注销链接

                if ($userLoggedIn) {
                    echo '<a href="exit.php" class="btn">注销</a>';
                } else {
                    echo '<a href="login.php" class="btn">登录</a>';
                    echo '<a href="register.php" class="btn">注册</a>';
                }
                ?>

                <!-- 如果用户未登录，点击发帖强制跳转到登录界面 -->

                <?php if ($userLoggedIn): ?>
                    <a href="post.php" class="btn">发帖</a>
                <?php else: ?>
                    <a href="login.php" class="btn" onclick="alert('请先登录'); window.location.href='login.php'; return false;">发帖</a>
                <?php endif; ?>

                <!-- 将用户信息移动到按钮组的左侧 -->

                <div class="user-info">
                    <?php if ($userLoggedIn): ?>
                        <p>欢迎您，<?php echo htmlspecialchars($user['username']); ?>!</p>
                    <?php else: ?>
                        <p>暂无用户登录</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <div class="container">

        <!-- 展示帖子标题，查询表中所有的帖子，放入数组后，foreach遍历数组展示 -->

        <?php
        foreach ($posts as $post) {
            $postTitleLink = $userLoggedIn ? 'viewPost.php?id=' . $post['id'] : 'login.php';
            $postTitleOnClick = $userLoggedIn ? '' : 'onclick="alert(\'请先登录\'); return login.php;"';
            echo "<div class='post-item'>
                    <div class='post-title'>
                        <a href='$postTitleLink' $postTitleOnClick>" . htmlspecialchars($post['title']) . "</a>
                    </div>
                    <div class='post-content'>" . htmlspecialchars(substr($post['content'], 0, 50)) . "...</div>
                    <div class='post-meta'>
                        <span>阅读：" . $post['view_count'] . "</span>
                        <span>回复：" . $post['answer_count'] . "</span>
                        <span>发布时间：" . $post['created_at'] . "</span>
                        <span>最新回答：" . ($post['latest_answer_at'] ? $post['latest_answer_at'] : '无') . "</span>
                    </div>
                 </div>";
        }
        ?>
    </div>

    <!-- 分页链接 -->

    <div class="pagination">
        <?php if ($totalPages > 1): ?>
            <div class="pagination-links">
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="btn">上一页</a>
                <?php endif; ?>
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="btn <?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="btn">下一页</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- 添加网页尾部 -->
 
<div class="footer">
    <p>&copy; 智界论坛·保留所有权利</p>
    <p>版权所有☆Qualan<sup>&copy;</sup> Q_L</p>
</div>
</body>

</html>